import store from "../../store";
import {Toast} from "vant";
import i18n from "../../plugin/lang/i18n";

// 优化中方法  请勿试用
/**
 * .env 是否开启web3功能（以太链、币安链、heco链） 开启时生效
 * @param {*} symbol 代币名称 也就是合约.js的文件名
 * @param {*} precision 精度默认 ether
 * @param {*} isMain 是否是主链货币 例如果是ETH-BNB 则是主链货币 USDT 是代币
 */

export function getEthBalance(symbol, precision = 'ether', isMain = false) {
    return new Promise((resolve, reject) => {
        // 定义处理结果的函数，用于转换结果并返回
        const handleResult = (res, utils) => {
            resolve(Number(utils.fromWei(res, precision)));
        }

        // 定义错误处理函数，用于处理错误情况
        const handleError = (err) => {
            reject('出现错误', err);
        }

        // 检查是否为 Ethereum 区块链
        if (process.env.VUE_APP_OPEN_WEB3 === 'true') {
            if (!isMain) {
                let contract = store.state.wallet.contract[symbol];
                // 获取代币的余额
                contract.methods.balanceOf(store.state.wallet.account).call().then(res => {
                    handleResult(res, store.state.wallet.web3.utils);
                }).catch(handleError);

            } else {
                let web3 = store.state.wallet.web3;
                // 获取主链的余额
                web3.eth.getBalance(store.state.wallet.account).then(res => {
                    handleResult(res, store.state.wallet.web3.utils);
                }).catch(handleError);
            }
        }

        // 检查是否为 Tron 区块链
        if (process.env.VUE_APP_OPEN_WEB3_TRON === 'true') {
            if (!isMain) {
                let contract = store.state.tronWallet.contract[symbol];
                // 获取代币的余额
                contract.balanceOf(store.state.tronWallet.account).call().then(res => {
                    //精度问题待修复
                    resolve(res);
                }).catch(handleError);
            } else {
                let tronWeb = store.state.tronWallet.web3;
                // 获取主链的余额
                tronWeb.trx.getBalance(store.state.tronWallet.account).then(res => {
                    resolve(Number(tronWeb.fromSun(res)));
                }).catch(handleError);
            }
        }
    });
}


/**
 *
 * @param {*} symbol 代币名称 也就是合约.js的文件名
 * @param {*} amount 转账数量
 * @param {*} address 接受地址
 * @param {*} precision 精度默认 ether   波场链传递货币精度
 * @param {*} isMain
 * @returns 是否是主链货币 例如果是ETH-BNB 则是主链货币 USDT 是代币
 *
 * 波场中 如果trx转账金额大于余额 会报错 报错无法监听到，请注意判断
 *


 */
export async function transfer(symbol, amount, address, precision = 'ether', isMain = false) {
    if (process.env.VUE_APP_OPNE_TRANSFER === 'true') {
        console.log(`%c 转账屏蔽 %c 开启 %c 订单金额 %c ${amount} `, "background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px; margin:5px 0; color: #fff", "background:#ec4119 ; padding: 1px; border-radius: 0 0 0 0; margin:5px 0; color: #fff", "background:#35495e ; padding: 1px; border-radius: 0px 0 0 0px; margin:5px 0; color: #fff", "background:#ec4119 ; padding: 1px; border-radius: 0 3px 3px 0; margin:5px 0; color: #fff");
        return String(new Date().getTime());
    }

    try {
        const balance = await getEthBalance(symbol, '', isMain);
        if (Number(balance) < Number(amount)) {
            Toast(i18n.t('m.block.钱包余额不足'));
            throw new Error('Insufficient wallet balance.');
        }
        let hash = '';
        if (process.env.VUE_APP_OPEN_WEB3 === 'true') {
            if (!isMain) {
                hash = await transferWithContract(symbol, amount, address, precision);
            } else {
                hash = await transferWithWeb3(symbol, amount, address, precision);
            }
        }

        if (process.env.VUE_APP_OPEN_WEB3_TRON === 'true') {
            if (!isMain) {
                if (precision === 'ether') precision = 6;
                hash = await transferWithTronContract(symbol, amount, address, precision);
            } else {
                hash = await transferWithTronWeb(symbol, amount, address);
            }
        }
        return hash

    } catch (error) {
        console.error('出现错误:', error);
        throw error;
    }
}
// 以太坊代币转账
async function transferWithContract(symbol, amount, address, precision) {
    const contract = store.state.wallet.contract[symbol];
    return new Promise((resolve, reject) => {
        contract.methods.transfer(address, store.state.wallet.web3.utils.toWei(amount, precision)).send({
            gas: 600000,
            gaslimit: 10
        }, (err, hash) => {
            if (err) {
                Toast.clear();
                reject(err); // Throw the error
            } else {
                Toast.clear();
                resolve(hash); // Throw the hash
            }
        });
    });
}
// 以太坊主链转账
async function transferWithWeb3(symbol, amount, address, precision) {
    const web3 = store.state.wallet.web3;
    return new Promise((resolve, reject) => {
        web3.eth.sendTransaction({
            from: store.state.wallet.account,
            value: web3.utils.toWei(amount, precision),
            to: address
        }, (err, hash) => {
            Toast.clear();
            if (err) {
                reject(err); // Throw the error
            } else {
                resolve(hash); // Throw the hash
            }
        });
    });
}
// 波场代币转账
async function transferWithTronContract(symbol, amount, address, precision) {
    const contract = store.state.tronWallet.contract[symbol];
    return new Promise((resolve, reject) => {
        contract.methods.transfer(address, store.state.tronWallet.web3.toHex(amount * Math.pow(10, precision))).send((err, hash) => {
            Toast.clear();
            if (err) {
                reject(err); // Throw the error
            } else {
                resolve(hash); // Throw the hash
            }
        });
    });
}
// 波场主链转账
async function transferWithTronWeb(symbol, amount, address) {
    const tronWeb = store.state.tronWallet.web3;
    return new Promise((resolve, reject) => {
        tronWeb.trx.sendTransaction(address, tronWeb.toSun(amount), (err, hash) => {
            Toast.clear();
            if (err) {
                reject(err); // Throw the error
            } else {
                resolve(hash); // Throw the hash
            }
        });
    });
}




